package org.example.what_mall.interceptor;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.what_mall.exception.GlobalCode;
import org.example.what_mall.exception.GlobalException;
import org.example.what_mall.util.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
import java.util.Objects;

//拦截用户未登录
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(Objects.equals(request.getMethod(), "OPTIONS")){
            return true;
        }

        String token = request.getHeader("token");
        if (token == null) {
            throw new GlobalException(GlobalCode.UNAUTHORIZED);
        }

        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries("what_mall:token:" + token);
        if (entries.isEmpty()) {
            throw new GlobalException(GlobalCode.UNAUTHORIZED);
        }

        if(UserHolder.getUser() == null) {
            throw new GlobalException(GlobalCode.PARAMETER_FAIL);
        }
        return true;
    }
}
